package juc.utils;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

public class CyclicBarrierExample3 {
    public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
        //第二个参数都结束后回调，这是比较好的方式
        final CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
        new Thread() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(4);
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        new Thread() {
            @Override
            public void run() {
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        TimeUnit.SECONDS.sleep(6);
        //count=parties；await的线程会抛出BrokenBarrierException
        //主线程调用，reset等价于initial、finished
        cyclicBarrier.reset();

    }
}
